//
//  OptionalViewController.m
//  HeXun
//
//  Created by Ibokan on 15/11/23.
//  Copyright © 2015年 LGC. All rights reserved.
//

#import "OptionalViewController.h"
#import "StockButtonModelView.h"
#import "StockModelView.h"
#import "GetXMLObject.h"
#import "SearchTableViewController.h"
#import "StockInfoModelViewController.h"
@interface OptionalViewController ()<UITextFieldDelegate>

//自选股按钮
@property (weak, nonatomic) IBOutlet UIButton *stockButton;

//自选基金按钮
@property (weak, nonatomic) IBOutlet UIButton *fundButton;

//搜索框
@property (weak, nonatomic) IBOutlet UITextField *searchTextField;

@property (assign,nonatomic) BOOL isSelectFund;
//自选股
@property(nonatomic,retain)StockModelView *stockView;

//自选基金
@property(nonatomic,retain)StockButtonModelView *stockButtonView;

@end

@implementation OptionalViewController

#pragma mark - itemDelegate
-(void)navigationItemToTabarControllerItem
{
    self.tabBarController.navigationItem.leftBarButtonItem = self.navigationItem.leftBarButtonItem;
    self.tabBarController.navigationItem.rightBarButtonItem = self.navigationItem.rightBarButtonItem;
    self.tabBarController.navigationItem.titleView = self.navigationItem.titleView;
    self.tabBarController.navigationItem.title = self.navigationItem.title;
    self.navigationController.navigationBarHidden = NO;
}

-(void)viewDidAppear:(BOOL)animated
{
    [self.stockView.table1 reloadData];
    [self.stockView.table2 reloadData];
}

- (void)addStockModleView
{
    _isSelectFund = NO;
    //添加model
    self.stockView = [StockModelView new];
    self.stockView.tag = 3;
    self.stockView.frame = CGRectMake(0, 152, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame));
    [self.view addSubview:self.stockView];
    
    //这是通过代码块自定义操作的operation的子类
    NSBlockOperation* cOperation = [NSBlockOperation blockOperationWithBlock:^{
        GetXMLObject* getXMLObject = [GetXMLObject new];
        
        NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
        
        NSString *stockFilePath = [documentsPath stringByAppendingPathComponent:@"stock.plist"];
        NSLog(@"stockFilePath: %@", stockFilePath);
        
        
        NSArray* array1 = [NSArray arrayWithContentsOfFile:stockFilePath];
        if (array1 != nil) {
            NSArray* array = [getXMLObject getStockArrayFromIDArray:array1 sort:4 type:0];
            self.stockView.stockArray = array;
        }
        NSBlockOperation* dOperation = [NSBlockOperation blockOperationWithBlock:^{
            [self.stockView.table1 reloadData];
            [self.stockView.table2 reloadData];
        }];
        //涉及更新UI的操作，就要创建包含这些操作的Operation对象，并把它放入主线程队列
        NSOperationQueue* mainQueue = [NSOperationQueue mainQueue];
        //当Operation放入主线程队列中，其操作就是子主线程中执行
        [mainQueue addOperation:dOperation];
    }];
    
    //创建Operation队列,operation只有在队列里才能跑
    NSOperationQueue* takeMoneyQueue = [NSOperationQueue new];
    
    [takeMoneyQueue addOperation:cOperation];
    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self addStockModleView];
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(action:) name:@"transfrom" object:nil];
    
    //设置搜索单行文本框代理
    self.searchTextField.delegate = self;
    self.searchTextField.keyboardType = UIKeyboardTypeNumberPad;
    
    //添加键盘附件栏
    UIButton *returnButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 0, 60)];
    [returnButton setTitle:@"返     回" forState:UIControlStateNormal];
    [returnButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    returnButton.titleLabel.font = [UIFont systemFontOfSize:25];
    returnButton.backgroundColor = [UIColor lightGrayColor];
    [returnButton addTarget:self action:@selector(returnButtonTouch) forControlEvents:UIControlEventTouchUpInside];
    
    _searchTextField.inputAccessoryView = returnButton;
    
}

#pragma mark - 搜索框回收键盘的方法
-(void)returnButtonTouch
{
    [self.searchTextField resignFirstResponder];
}

#pragma mark - 限制搜索框输入的内容不超过6个字符
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //利用传入的参数“预测”文本改变之后的结果
    
    NSString *futureText = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    //限制字符串最大长度为6
    if (futureText.length <= 6)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

#pragma mark - 搜索按钮触发的方法
- (IBAction)searchButtonTouch:(UIButton *)sender
{
    SearchTableViewController *searchController = [SearchTableViewController new];
    searchController.searchBarText = self.searchTextField.text;
    
    //跳转到搜索结果控制器
    [self.navigationController pushViewController:searchController animated:YES];
}


-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"transfrom" object:nil];
}

#pragma mark - 跳转到stockInfoModelViewController的方法
- (void)action:(NSNotification* )notification
{
    if ([notification.object isKindOfClass:[StockModelView class]])
    {
        StockModelView* stockModelView = notification.object;
        if (stockModelView.tag == 3)
        {
            UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            StockInfoModelViewController* stockInfoModelViewController = [storyboard instantiateViewControllerWithIdentifier:@"stockInfoViewModel"];
            if (_isSelectFund == NO)
            {
                NSLog(@"%ld",[self.stockView.table2 indexPathForSelectedRow].row);
                stockInfoModelViewController.pointArr = self.stockView.stockArray[[self.stockView.table2 indexPathForSelectedRow].row ];
            }
            else
            {
                stockInfoModelViewController.pointArr = self.stockButtonView.stockArray[[self.stockButtonView.table2 indexPathForSelectedRow].row ];
            }
            [self.navigationController pushViewController:stockInfoModelViewController animated:YES];
        }
    }
    if ([notification.object isKindOfClass:[StockButtonModelView class]])
    {
        UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        StockInfoModelViewController* stockInfoModelViewController = [storyboard instantiateViewControllerWithIdentifier:@"stockInfoViewModel"];
        if (_isSelectFund == YES)
        {
            NSLog(@"%ld",[self.stockButtonView.table2 indexPathForSelectedRow].row);
            stockInfoModelViewController.segmentIndex = 4;
            stockInfoModelViewController.pointArr = self.stockButtonView.stockArray[[self.stockButtonView.table2 indexPathForSelectedRow].row ];
        }
        else
        {
            stockInfoModelViewController.pointArr = self.stockView.stockArray[[self.stockView.table2 indexPathForSelectedRow].row ];
        }
        [self.navigationController pushViewController:stockInfoModelViewController animated:YES];

    }
}


//自选股按钮
- (IBAction)stockButton:(id)sender
{
    _isSelectFund = NO;
    //移除view
    [self.stockButtonView removeFromSuperview];
    [self.stockView removeFromSuperview];
    [self removeButton];
    
    //改变颜色，添加下划线
    self.fundButton.titleLabel.textColor = [UIColor blackColor];
    NSMutableAttributedString *fundString = [[NSMutableAttributedString alloc]initWithString:@"自选基金"];
    [self.fundButton setAttributedTitle:fundString forState:UIControlStateNormal];

    
    NSMutableAttributedString *stockString = [[NSMutableAttributedString alloc]initWithString:@"自选股"];
    NSRange range = {0,[stockString length]};
    [stockString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:range];
    self.stockButton.titleLabel.textColor = [UIColor redColor];
    [self.stockButton setAttributedTitle:stockString forState:UIControlStateNormal];
    
    [self addStockModleView];
}

//自选基金
- (IBAction)fundButton:(id)sender {
    _isSelectFund = YES;
    //清空view
    [self.stockView removeFromSuperview];
    [self.stockButtonView removeFromSuperview];
    [self removeButton];
    
    //变红色，添加下划线
    self.stockButton.titleLabel.textColor = [UIColor blackColor];
    NSMutableAttributedString *stockString = [[NSMutableAttributedString alloc]initWithString:@"自选股"];
    [self.stockButton setAttributedTitle:stockString forState:UIControlStateNormal];
    
    NSMutableAttributedString *fundString = [[NSMutableAttributedString alloc]initWithString:@"自选基金"];
    NSRange range = {0,[fundString length]};
    [fundString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:range];
    self.fundButton.titleLabel.textColor = [UIColor redColor];
    [self.fundButton setAttributedTitle:fundString forState:UIControlStateNormal];
    
    //添加按钮
    [self createThreeButton];
    
    //添加基金model
    self.stockButtonView = [StockButtonModelView new];
    self.stockButtonView.frame = CGRectMake(0, 192, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame));
    [self.view addSubview:self.stockButtonView];
    
    
    //这是通过代码块自定义操作的operation的子类
    NSBlockOperation* cOperation = [NSBlockOperation blockOperationWithBlock:^{
        NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
        
        NSString *stockFilePath = [documentsPath stringByAppendingPathComponent:@"fund.plist"];
        NSLog(@"stockFilePath: %@", stockFilePath);
        
        
        NSArray* array1 = [NSArray arrayWithContentsOfFile:stockFilePath];
        
        
        if (array1 != nil)
        {
            NSMutableArray* tempArr = [NSMutableArray new];
            for (NSDictionary* dic in array1)
            {
                StockModel* stockModel = [StockModel new];
                stockModel.newest = dic[@"newest"];
                stockModel.stockName = dic[@"name"];
                stockModel.fld_time = dic[@"time"];
                stockModel.upsAndDowns = dic[@"upAndDown"];
                stockModel.amountofIncrease = dic[@"amountrise"];
                [tempArr addObject:stockModel];
            }
            NSArray* fundArr = [NSArray arrayWithArray:tempArr];
            self.stockButtonView.stockArray = fundArr;
        }

        

        NSBlockOperation* dOperation = [NSBlockOperation blockOperationWithBlock:^{
            [self.stockButtonView.table1 reloadData];
            [self.stockButtonView.table2 reloadData];
        }];
        //涉及更新UI的操作，就要创建包含这些操作的Operation对象，并把它放入主线程队列
        NSOperationQueue* mainQueue = [NSOperationQueue mainQueue];
        //当Operation放入主线程队列中，其操作就是子主线程中执行
        [mainQueue addOperation:dOperation];
    }];
    
    //创建Operation队列,operation只有在队列里才能跑
    NSOperationQueue* takeMoneyQueue = [NSOperationQueue new];
    
    [takeMoneyQueue addOperation:cOperation];
    
}

#pragma mark - 创建3个按钮
-(void)createThreeButton
{
    for (int i = 0 ; i < 3; i++) {
        UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(40 + i * 100, 164, 60, 26)];
        switch (i) {
            case 0:
                [button setTitle:@"封闭式" forState:UIControlStateNormal];
                break;
            case 1:
                [button setTitle:@"开放式" forState:UIControlStateNormal];
                break;
            case 2:
                [button setTitle:@"封闭式" forState:UIControlStateNormal];
                break;
            default:
                break;
        }
        //button文字默认白色，现在设置为黑色
        button.titleLabel.font = [UIFont fontWithName:@"Courier" size:15.0f];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        button.tag = 11 + i;
        [button addTarget:self action:@selector(buttonPressedStateChange:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
    }
}

#pragma mark - 移除button
-(void)removeButton
{
    for (int i = 0; i < 3; i++) {
        UIButton *button = [self.view viewWithTag:11 + i ];
        [button removeFromSuperview];
    }
}

#pragma mark - 选中的时候深蓝色圆角矩形白色字体
-(void)buttonPressedStateChange:(UIButton*)button
{
    for (int i = 0; i < 3; i++) {
        UIButton *testButton = [self.view viewWithTag:11 + i];
        
        if (testButton.tag == button.tag) {
            [self changeState:testButton];
        }
        else
        {
            [self returnState:testButton];
        }
    }
}

#pragma mark - 选中的时候深蓝色圆角矩形白色字体
-(void)changeState:(UIButton*)button
{
    button.layer.borderWidth = 1.5;
    button.layer.borderColor = (__bridge CGColorRef _Nullable)([UIColor blackColor]);
    //设置圆角
    button.layer.cornerRadius = 5;
    UIColor *color = [UIColor colorWithRed:0.0313f green:0.18f blue:0.33f alpha:1];
    button.backgroundColor = color;
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
}


#pragma mark - 按钮返回普通状态
-(void)returnState:(UIButton*)button
{
    button.layer.cornerRadius = 0;
    button.backgroundColor =  [UIColor whiteColor];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
